import React, { useState, useEffect, useContext } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Space,
  Input,
  Form,
  Grid,
  Message,
  Tag,
  Modal,
  Image,
  Tooltip,
  Popconfirm,
} from '@arco-design/web-react';
import { GlobalContext } from '@/context';
import { IconSearch, IconRefresh } from '@arco-design/web-react/icon';
import styles from './style/index.module.less';
import './mock';
import { getUserList, delUser } from '@/api/user';
import dayjs from 'dayjs';

function User() {
  const { Row, Col } = Grid;
  const { useForm } = Form;
  const [form] = useForm();
  const { lang } = useContext(GlobalContext);
  const colSpan = lang === 'zh-CN' ? 8 : 12;

  // 表头
  const columns = [
    {
      title: '昵称',
      dataIndex: 'nickName',
      width: 100,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      width: 60,
      render: (_, record) => {
        return <Image width={50} height={50} src={record.avatar}></Image>;
      },
    },
    {
      title: '来源',
      width: 80,
      dataIndex: 'provider',
    },
    {
      title: 'Email',
      dataIndex: 'email',
    },

    {
      title: '收藏数量',
      dataIndex: 'articleIds',
      render: (_, record) => {
        return <Tag color="orange">{record.articleIds?.length}</Tag>;
      },
    },

    {
      title: '简介',
      width: 400,
      dataIndex: 'introduction',
      render: (text) => {
        return (
          <Tooltip position="tl" content={text}>
            {text}
          </Tooltip>
        );
      },
    },
    {
      title: '注册时间',
      dataIndex: 'registerTime',
      width: 180,
      render: (x) => (x ? dayjs(x).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },

    {
      title: '操作',
      dataIndex: 'operations',
      render: (_, record) => (
        <div className={styles.operations}>
          <Popconfirm
            title="Are you sure you want to delete?"
            onOk={() => onDelete(record)}
          >
            <Button type="text" status="danger" size="small">
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  // 获取表格数据
  async function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    const params = {
      page: current,
      pageSize,
      ...formParams,
    };
    try {
      const res: any = await getUserList(params);
      console.log(res)
      if (res.code === 200) {
        setData(res.data.list);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.data.total,
        });
        setLoading(false);
      } else {
      }
    } catch (error) {
      console.error(error);
    }
  }

  // 分页
  function onChangeTable(pagination) {
    setPatination(pagination);
  }

  // 查询
  function handleSearch() {
    setFormParams(form.getFields());
  }

  // 重置
  const handleReset = () => {
    form.resetFields();
  };

  // 删除
  const onDelete = async (row) => {
    console.log(row);
    setLoading(true);
    try {
      const res: any = await delUser(row);
      if (res.code === 200) {
        Message.success(res.msg);
        fetchData();
      } else {
        Message.error(res.msg);
        setLoading(false);
      }
    } catch (error) {
      console.error(error);
      setLoading(false);
    }
  };

  return (
    <div>
      <Card
        title="用户列表"
        headerStyle={{ border: 'none', height: 'auto', paddingTop: '20px' }}
      >
        <div className={styles['search-form-wrapper']}>
          <Form
            form={form}
            className={styles['search-form']}
            labelAlign="left"
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
          >
            <Row gutter={24}>
              <Col span={colSpan}>
                <Form.Item label="名称" field="name">
                  <Input placeholder="请输入名称" allowClear />
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <div className={styles['right-button']}>
            <Space>
              <Button
                type="primary"
                icon={<IconSearch />}
                onClick={handleSearch}
              >
                查询
              </Button>
              <Button icon={<IconRefresh />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </div>
        </div>
        <Table
          rowKey="_id"
          loading={loading}
          onChange={onChangeTable}
          pagination={pagination}
          columns={columns}
          data={data}
        />
      </Card>
    </div>
  );
}

export default User;
